package com.csnf.servlet;

import com.csnf.entity.Admin;
import com.csnf.entity.User;
import com.csnf.service.AdminService;
import com.csnf.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    AdminService adminService = new AdminService();
    UserService userService = new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        System.out.println(username);
        if("admin".equals(username)){
            PrintWriter writer = response.getWriter();
            writer.println("1.jpg");
            writer.flush();  //刷新输出流缓存
        }
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Admin admin = null;
        try {
            admin = adminService.getAdminByNameAndPwd(username, password);  //通过用户名密码找用户信息
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(admin!=null){
            //把用户信息存入HttpSession 中方便会话断开前都能拿到用户信息
            System.out.println(admin);
            HttpSession session = request.getSession();
            session.setAttribute("admin",admin);    //admin信息放入session
            try {
                List<User> userList = userService.getAll();  //获取用户的所有信息
                request.setAttribute("userList",userList); //将用户信息通过请求对象发送前台
            } catch (SQLException e) {
                e.printStackTrace();
            }
            request.getRequestDispatcher("/success.jsp").forward(request,response);  //转发到主页
        }else{
            //转发
            request.setAttribute("msg","密码错误！");
            request.getRequestDispatcher("index.jsp").forward(request,response);
        }
    }

    

}
